<?php

namespace App\Actions;


use App\Constants\CodeData;
use App\Dao\AnchorDao;
use App\Dao\AnchorTaskDao;
use App\Dao\ClosenessDao;
use App\Dao\CommonSettingDao;
use App\Dao\PayCallDao;
use App\Dao\SettingDao;
use App\Dao\UserDao;
use App\Model\Gift;
use App\Model\IncomeExpense;
use App\Model\PayCall;
use App\Model\User;
use App\Model\UserCardPack;
use App\Model\UserScore;
use App\Services\Mission\MissionQueue;
use App\Services\PushMessageService;
use App\Services\User\UserWelfareService;
use App\Services\YunXinCloud\WyyClientService;
use App\Utils\FunUtil;
use App\Utils\LoggerUtil;
use App\Utils\MemcacheClient;
use App\Utils\RedisClient;
use Hyperf\DbConnection\Db;
use Throwable;
use function Hyperf\Config\config;
use function Hyperf\Translation\trans;

class PaycallAction
{

    /**
     * Note - 结算
     * DateTime 2024/8/2 12:35
     * User Admin
     * @param $call_id
     * @param $is_anchor
     * @param $hand_up_uid
     * @param $update_arr
     * @param int $extend
     * @return array
     */
    public function settleCall($call_id, $is_anchor, $hand_up_uid, $update_arr, int $extend = 0): array
    {

        $payCall = PayCallDao::getInstance()->getCallCache($call_id, true);
        $anchor_id = $payCall["anchor_id"];
        $user_id = $payCall["user_id"];

        if (!empty($update_arr['end_time'])) {
            $payCall['end_time'] = $update_arr['end_time'];
        }

        if ($payCall['start_time'] == 0) {
            $update_arr['end_time'] = 0;
        }

        // 修改免费时长
        if (($payCall['match_id'] == 0 || $payCall['match_id'] != 0) && ($payCall['end_time'] - $payCall['start_time']) < $payCall['free_video_time']) {
            $update_arr['free_video_time'] = $payCall['end_time'] - $payCall['start_time'];
            $payCall['free_video_time'] = $update_arr['free_video_time'];
        }

        //女用户结算
        if (isset($update_arr['extend']) && in_array($update_arr['extend'], ['14', '24', '15', '25', '12', '21', '22', '13', '23'])) {
            $_rs = $this->getProfitForCall($payCall, false);
        } else {
            $_rs = $this->getProfitForCall($payCall, $is_anchor);
        }
        LoggerUtil::write("call_alive", ['call_id' => $call_id, 'line' => 5, 'url' => 'settleCall', 'res' => $_rs, 'update_arr' => $update_arr, 'pay_call' => $payCall]);

        if ($_rs['code'] == 1) {
            $payCall = $_rs['paycall'];
        }
        if ($_rs['code'] == -2) {
            $payCall = PayCallDao::getInstance()->getCallCache($call_id, true);
        }

        if (!empty($update_arr)) {
            if ($extend > 0) {
                $update_arr['extend'] = $extend;
            }

            try {
                // $res = $payCallModel->updateByWhere($update_arr, "id = $call_id and status = 0");
                $res = PayCall::query()->where('id', $call_id)->update($update_arr);
                LoggerUtil::write("call_alive", ['call_id' => $call_id, 'line' => 6, 'url' => 'settleCall', 'res' => $res, 'update_arr' => $update_arr]);
            } catch (Throwable $e) {
                LoggerUtil::write("call_alive", ['call_id' => $call_id, 'line' => 7, 'url' => 'settleCall', 'res' => $e]);
            }

            MemcacheClient::getInstance()->delete('the_pay_call_' . $call_id);
        }

        if (!$is_anchor) {
            $anchor_info = AnchorDao::getInstance()->findAnchorInfoCache($anchor_id);
            $balanceData = showBalanceForUser($payCall, $anchor_info);
        } else {
            // $userModel = new UserModel();
            // $user_info = $userModel->findById($user_id, 'id,nickname,head_image');
            $user_info = User::query()->select(['id', 'nickname', 'head_image'])->where('id', $user_id)->first();
            $balanceData = showBalanceForAnchor($payCall, $user_info);

            // 判断是免费通话给主播发送消息提示
            // if ($payCall['end_time'] > 0 && $payCall['profit'] == 0 && $payCall['free_video_time'] == 30) {
            //     $this->sendAnchorSubsidyMsg($anchor_id);
            // }
        }
        LoggerUtil::write("call_alive", ['call_id' => $call_id, 'line' => 8, 'url' => 'settleCall', 'balanceData' => $balanceData, 'pay_call' => $payCall]);
        MemcacheClient::getInstance()->delete('last_pay_call_item_' . $anchor_id);
        MemcacheClient::getInstance()->delete('deduct_time_' . $payCall['id']);

        if (isGiftVersion() && !empty($balanceData)) {
            $giftModel = new Gift();
            if (!$is_anchor) {
                //算出用户送礼支出
                $gift_amount = $giftModel->getGiftCost($hand_up_uid, $call_id);
            } else {
                //算出主播收礼收入
                $gift_amount = $giftModel->getGiftProfit($hand_up_uid, $call_id);
            }
            $balanceData['gift_amount'] = $gift_amount;

//            $mine = $userModel->findUserInfoById($uid);
//            if (!$is_anchor) {
//                $balanceData['account'] = (int)$mine['gift_count'];
//            } else {
//                $balanceData['account'] = (float)$mine['integrate_usable_count'];
//            }

        }
        $balanceData['super_free_video_time'] = 0;

        $duration = $payCall['end_time'] - $payCall['start_time'];
        if ($duration >= 1200) {
            if ($payCall['type'] == 1) {
                MissionQueue::call($user_id);
                MissionQueue::call($anchor_id);
            } else {
                MissionQueue::audio($user_id);
            }
        }

        return $balanceData;
    }


    /**
     * 用户通话(视频或语音)消费
     * @param $paycall
     * @return array
     */
    public function payForCall($paycall)
    {
        try {
            Db::beginTransaction();

            $call_id = $paycall['id'];
            $userId = $paycall['user_id'];
            $anchorId = $paycall['anchor_id'];
            $amount = $paycall['price']; //金币
            $userInfo = User::findUserInfoById($userId);

            // 处理匹配逻辑
            if ($paycall['match_id'] != 0 && $paycall['card_id'] == 0) {
                $setting = SettingDao::getInstance();
                $free_time1 = $setting->getOne("match_have_free_time");   // 金币足够时免费时长
                // $free_time2 = $setting->getOne("match_not_free_time");    // 金币不足时免费时长
                if (empty($paycall['start_time']) && empty($paycall['end_time'])) {
                    // $this->payCallModel->updateByWhere(['free_video_time' => $free_time1], "id = $call_id and status = 0");
                    PayCall::query()->where('id', $call_id)->where('status', 0)->update(['free_video_time' => $free_time1]);

                    Db::commit();
                    return array('code' => 1, 'msg' => '匹配初始化！', 'type' => 1);
                }
                $time = time() - $paycall['start_time'];
                if ($time < $free_time1) {
                    Db::commit();
                    return array('code' => 1, 'msg' => '支付成功', 'type' => 2);
                }
            } else {
                if ($userInfo['gift_count'] + $userInfo['sys_send_count'] + $userInfo['recharge_send_count'] < $amount) {
                    throw new \Exception("金币不足", -1);
                }
                // 不是匹配，判断是否使用体验卡
                if ($paycall['card_id'] > 0 && ($paycall['start_time'] == 0 || $paycall['last_pay_time'] == 0)) {
                    // 男用户使用体验卡
                    // $r1 = $this->payCallModel->update($paycall['card_id'], ['status' => 1, 'use_time' => time(), 'user_id' => $paycall['anchor_id']], "tb_user_card_pack");
                    $r1 = UserCardPack::query()->where('id', $paycall['card_id'])->update(['status' => 1, 'use_time' => time(), 'user_id' => $paycall['anchor_id']]);

                    // 女用户获得体验卡
                    // $r2 = $this->payCallModel->insert([
                    //     'uid' => $paycall['anchor_id'],
                    //     'card_type' => 1,
                    //     'status' => 0,
                    //     'get_time' => time(),
                    //     'use_time' => 0
                    // ], "tb_user_card_pack");
                    $r2 = UserCardPack::query()->insert([
                        'uid' => $paycall['anchor_id'],
                        'card_type' => 1,
                        'status' => 0,
                        'get_time' => time(),
                        'use_time' => 0
                    ]);

                    // $this->payCallModel->updateByWhere(['free_video_time' => 60, 'last_pay_time' => time()], "id = $call_id and status = 0");
                    PayCall::query()->where('id', $call_id)->where('status', 0)->update(['free_video_time' => 60, 'last_pay_time' => time()]);

                    if (!$r1 || !$r2) {
                        throw new \Exception("体验卡使用失败", -1);
                    }

                    Db::commit();
                    return array('code' => 1, 'msg' => '支付成功');
                }

            }

            // 获取需消耗得金币数量
            $checkGold = checkUserGoldCount($userInfo, $amount, 2);
            if ($checkGold) {
                // extract($checkGold);
                $gift_count = $checkGold['gift_count']; // 普通金币
                $chat_count = $checkGold['chat_count'];// 聊币
                $sys_send_count = $checkGold['sys_send_count']; // 系统赠送金币
                $recharge_send_count = $checkGold['recharge_send_count'];// 充值赠送金币

                // return compact("gift_count",'chat_count','sys_send_count','recharge_send_count');
            } else {
                throw new \Exception("金币余额不足", -1);
            }

            $gold_from = compact("gift_count", 'sys_send_count', 'recharge_send_count');

            $redis = RedisClient::getInstance();
            // 扣除系统增送金币
            if ($sys_send_count > 0) {
                // $rs = $this->userModel->updateByWhereSet("sys_send_count=sys_send_count-{$sys_send_count}", "id={$userId}");
                $rs = User::query()->where('id', $userId)->update(['sys_send_count' => Db::raw("sys_send_count-{$sys_send_count}")]);
                if (!$rs) {
                    throw new \Exception("用户扣除金币失败", -1);
                }

                // 记录当前通话扣除系统赠送金币数量
                $num = $redis->get("call_system_send_{$call_id}");    //男用户消费系统赠送金币
                if ($num) {
                    $redis->set("call_system_send_{$call_id}", $num + $sys_send_count, 600);
                    $gold_from['sys_send_count'] = $num + $sys_send_count;
                } else {
                    $redis->set("call_system_send_{$call_id}", $sys_send_count, 600);
                    $gold_from['sys_send_count'] = $sys_send_count;
                }
            } else {
                // 通话扣除系统赠送金币数量
                $num = $redis->get("call_system_send_{$call_id}");    //男用户消费系统赠送金币
                $gold_from['sys_send_count'] = intval($num);
            }

            // 扣除充值赠送金币
            if ($recharge_send_count > 0) {
                // $rs = $this->userModel->updateByWhereSet("recharge_send_count=recharge_send_count-{$recharge_send_count}", "id={$userId}");
                $rs = User::query()->where('id', $userId)->update(['recharge_send_count' => Db::raw("recharge_send_count-{$recharge_send_count}")]);
                if (!$rs) {
                    throw new \Exception("用户扣除金币失败", -1);
                }

                // 记录当前通话扣除系统赠送金币数量
                $num = $redis->get("call_recharge_send_{$call_id}");    //男用户消费系统赠送金币
                if ($num) {
                    $redis->set("call_recharge_send_{$call_id}", $num + $recharge_send_count, 600);
                    $gold_from['recharge_send_count'] = $recharge_send_count + $num;
                } else {
                    $redis->set("call_recharge_send_{$call_id}", $recharge_send_count, 600);
                    $gold_from['recharge_send_count'] = $recharge_send_count;
                }
            } else {
                // 通话扣除系统赠送金币数量
                $num = $redis->get("call_recharge_send_{$call_id}");    //男用户消费系统赠送金币
                $gold_from['recharge_send_count'] = intval($num);
            }

            // 扣除普通金币
            if ($gift_count > 0) {
                $rs = UserDao::getInstance()->reduceUserAccount($userId, $gift_count);
                if (!$rs) {
                    throw new \Exception("用户扣除金币失败", -1);
                }
            }

            $gold_from['gift_count'] = $paycall['fare'] > 0 ? ($paycall['fare'] + $gift_count - $gold_from['sys_send_count'] - $gold_from['recharge_send_count']) : $gift_count;

            // 增加男用户财富值，女用户魅力值
            $r = UserDao::getInstance()->addUserWealth($userId, $anchorId, $amount);
            // 记录用户亲密度
            $result = ClosenessDao::write($userId, $anchorId, $amount);

            $type = 2;
            $sub_type = $paycall['type'] == 1 ? 2 : 4;
            $amount_type = 1;
            $account = $userInfo['gift_count'] + $userInfo['sys_send_count'] + $userInfo['recharge_send_count'] - $amount;

            // $his = $this->_incomeExpenseModel->find("*", "type=? AND sub_type=? AND amount_type=? AND extend=?", [$type, $sub_type, $amount_type, $call_id]);
            $his = IncomeExpense::query()
                ->where('type', $type)
                ->where('sub_type', $sub_type)
                ->where('amount_type', $amount_type)
                ->where('extend', $call_id)
                ->first();
            if ($his) {
                $rs = IncomeExpense::incrementCallAmount($his["id"], $amount, $account, $gold_from);
                if (!$rs) {
                    throw new \Exception("更新支出记录失败", -3);
                }
            } else {
                //插入支出记录
                // $anchorInfo = $this->userModel->find("id,package,channel,version_code", "id=?", [$anchorId]);
                $anchorInfo = User::query()->select('package', 'channel', 'version_code')->where('id', $anchorId)->first();
                $user_expense['uid'] = $userId;
                $user_expense['type'] = $type;//支出
                $user_expense['sub_type'] = $sub_type; //视频通话支出
                $user_expense['amount_type'] = $amount_type; //金币
                $user_expense['amount'] = $amount;
                $user_expense['account'] = $account;
                $user_expense['user_id'] = $anchorId;
                $user_expense['ext'] = json_encode(['p' => $anchorInfo['package'], 'v' => $anchorInfo['version_code'], 'c' => $anchorInfo['channel']]);
                $user_expense['ctime'] = time();
                $user_expense = $this->getExpense($call_id, $user_expense, $userInfo);
                $user_expense['gold_from'] = json_encode($gold_from);
                // $rs = $this->payCallModel->insert($user_expense, 'tb_income_expense');
                $rs = IncomeExpense::query()->insert($user_expense);
                if (!$rs) {
                    throw new \Exception("插入支出记录失败", -3);
                }
            }

            //更新通话记录
            $rs = PayCallDao::getInstance()->updateCallAmount($amount, $call_id, $userInfo['gift_count'] + $userInfo['sys_send_count'] + $userInfo['recharge_send_count'], 1);
            if (!$rs) {
                throw new \Exception("更新通话记录失败", -2);
            }

            MemcacheClient::getInstance()->delete("userInfo_" . $userId);
            MemcacheClient::getInstance()->delete('the_pay_call_' . $call_id);

            Db::commit();

            return array('code' => 1, 'msg' => '支付成功');
        } catch (Throwable $e) {
            Db::rollBack();
            LoggerUtil::write('pay_for_call.log', [$e->getMessage(), $e->getFile(), $e->getLine()]);
            return array('code' => $e->getCode(), 'msg' => $e->getMessage());
        }
    }


    /**
     * 用户发送消息扣费
     * @param $uid //用户id
     * @param $user_id //对方id
     * @param $fare //扣出的金币
     * @return array
     */
    public function payForMessage($uid, $user_id, $fare, $rate, $message_id = '', $is_limit = 0, $break_rule = 0)
    {
        try {
            Db::beginTransaction();

            if ($fare <= 0) {
                throw new \Exception("不消耗金币");
            }

            // $anchorModel = new AnchorModel();
            $anchor = AnchorDao::getInstance()->findAnchorInfoById($user_id);
            $rate = $anchor['rate'];
            $profit = 0;

            $rs0 = User::findUserInfoById($uid);

            // $chat_count = 0;    // 聊币
            // $gift_count = 0;    // 普通金币
            // $sys_send_count = 0;    // 系统赠送金币
            // $recharge_send_count = 0;    // 充值赠送金币

            // 获取需消耗得金币数量
            $checkGold = checkUserGoldCount($rs0, $fare, 3);
            if ($checkGold) {
                // extract($checkGold);
                $gift_count = $checkGold['gift_count']; // 普通金币
                $chat_count = $checkGold['chat_count'];// 聊币
                $sys_send_count = $checkGold['sys_send_count']; // 系统赠送金币
                $recharge_send_count = $checkGold['recharge_send_count'];// 充值赠送金币
            } else {
                throw new \Exception("金币不足", -1);
            }

            $rate_arr = [];
            // 扣除聊币
            if ($chat_count > 0) {
                $sys_rate = CommonSettingDao::getValue("system_send_gold_rate");
                $rate_arr['system_send_rate'] = $sys_rate;
                $profit = bcadd($profit, $chat_count * $sys_rate, 2);

                $rs_1 = UserDao::getInstance()->reduceUserChatCount($uid, $chat_count);
                if (!$rs_1) {
                    throw new \Exception("用户扣除金币失败");
                }
            }

            // 扣除系统增送金币
            if ($sys_send_count > 0) {
                $sys_rate = CommonSettingDao::getValue("system_send_gold_rate");
                $rate_arr['system_send_rate'] = $sys_rate;
                $profit = bcadd($profit, $sys_send_count * $sys_rate, 2);
                // $rs = $this->userModel->updateByWhereSet("sys_send_count=sys_send_count-{$sys_send_count}", "id={$uid}");
                $rs = User::query()->where('id', $uid)->update(['sys_send_count' => Db::raw("sys_send_count-{$sys_send_count}")]);
                if (!$rs) {
                    throw new \Exception("用户扣除金币失败", -1);
                }
            }

            // 扣除充值赠送金币
            if ($recharge_send_count > 0) {
                $rec_rate = CommonSettingDao::getValue("recharge_send_gold_rate");
                $rate_arr['recharge_send_rate'] = $rec_rate;
                $profit = bcadd($profit, $recharge_send_count * $rec_rate, 2);
                // $rs = $this->userModel->updateByWhereSet("recharge_send_count=recharge_send_count-{$recharge_send_count}", "id={$uid}");
                $rs = User::query()->where('id', $uid)->update(['recharge_send_count' => Db::raw("recharge_send_count-{$recharge_send_count}")]);
                if (!$rs) {
                    throw new \Exception("用户扣除金币失败", -1);
                }
            }

            // 扣除普通金币
            if ($gift_count > 0) {
                $profit = bcadd($profit, $gift_count * $rate, 2);
                $rs = UserDao::getInstance()->reduceUserAccount($uid, $gift_count);
                if (!$rs) {
                    throw new \Exception("用户扣除金币失败", -1);
                }
            }

            $rs4 = User::findUserInfoById($user_id);
            //插入用户支出流水
            $user_expense = array();
            $user_expense['uid'] = $uid;
            $user_expense['type'] = 2;//支出
            $user_expense['sub_type'] = 15; //发送消息支出
            $user_expense['amount_type'] = 1; // 金币
            $user_expense['amount'] = $fare;
            $user_expense['account'] = $rs0['gift_count'] + $rs0['chat_count'] + $rs0['sys_send_count'] + $rs0['recharge_send_count'] - $fare;
            $user_expense['user_id'] = $user_id;
            $user_expense['ext'] = json_encode(["p" => $rs4['package'], 'v' => $rs4['version_code'], 'c' => $rs4['channel']]);
            $user_expense['ctime'] = time();
            $user_expense = $this->getExpense($message_id, $user_expense, $rs0);
            $user_expense['gold_from'] = json_encode(array_merge($checkGold, $rate_arr));

            // $rs_2 = $this->payCallModel->insert($user_expense, 'tb_income_expense');
            $rs_2 = IncomeExpense::query()->insert($user_expense);
            if (!$rs_2) {
                throw new \Exception("插入支出记录失败");
            }

            // 判断用余额更新客户端数据
            if ($user_expense['account'] < 9) {
                $new_message = json_encode(['event' => 'update_myinfo', 'uid' => $uid]);
                PushMessageService::putYunXinSendAttachMsgQueue(config("yunxin.from"), $uid, $new_message);
                // (new WyyClient())->putAttachMsgQueue(config("yunxin.from"), $uid, $new_message);
            }


            // 判断是否开启回复消息获得收益
            if (CommonSettingDao::getValue('REPLY_INCOME') == 0) {
                // 风险用户发消息女用户不计收益
                if ($is_limit) {
                    // 记录临时亲密度
                    $redis = RedisClient::getInstance();
                    $tmp = $redis->hGet("tmp_closeness:{$uid}", $user_id) ?: 0;
                    $redis->hSet("tmp_closeness:{$uid}", $user_id, $tmp + $fare);
                    Db::commit();
                    return array('code' => 0, 'gold' => $fare, 'gold_from' => $user_expense['gold_from'], 'expend_id' => $rs_2);
                }
                // 记录用户亲密度
                ClosenessDao::write($uid, $user_id, $fare);
                // 增加男用户财富值，女用户魅力值
                UserDao::getInstance()->addUserWealth($uid, $user_id, $fare);

                // 违规消息扣费加亲密度
                if ($break_rule) {
                    Db::commit();
                    return array('code' => 0, 'gold' => $fare, 'gold_from' => $user_expense['gold_from'], 'expend_id' => $rs_2);
                }

                if ($profit > 0) {
                    //增加积分
                    $rs3 = UserDao::getInstance()->addAnchorAccount($user_id, $profit);
                    if (!$rs3) {
                        throw new \Exception("增加积分失败");
                    }

                    if (!$rs4) {
                        throw new \Exception("查询用户信息失败");
                    }

                    $anchor_income = array();
                    $anchor_income['uid'] = $user_id;
                    $anchor_income['type'] = 1;//收入
                    $anchor_income['sub_type'] = 7;//接收信息收入
                    $anchor_income['amount_type'] = 2; // 积分
                    $anchor_income['amount'] = $profit;
                    $anchor_income['account'] = $rs4['integrate_usable_count'] + $profit;
                    $anchor_income['user_id'] = $uid;
                    $anchor_income['ext'] = json_encode(["p" => $rs0['package'], 'v' => $rs0['version_code'], 'c' => $rs0['channel']]);
                    $anchor_income['ctime'] = time();
                    $anchor_income['extend'] = '';
                    $anchor_income['rate'] = $rate * 100;
                    $anchor_income['from'] = intval($rs4['from']);
                    $anchor_income['ip'] = FunUtil::getClientIp();
                    $anchor_income['version_code'] = intval($rs4['version_code']);
                    $anchor_income['channel'] = $rs4['channel'];
                    $anchor_income['package'] = $rs4['package'];
                    $anchor_income['guild_num'] = $rs4["guild_num"];
                    $anchor_income['gold_from'] = json_encode(array_merge($checkGold, $rate_arr));
                    // $rs5 = $this->payCallModel->insert($anchor_income, 'tb_income_expense');
                    $rs5 = IncomeExpense::query()->insert($anchor_income);
                    if (!$rs5) {
                        throw new \Exception("插入收入记录失败");
                    }
                    //邀请用户分成
//                if (!empty($rs4['inviteUid'])) {
//                    (new \lib\services\user\UserWelfareService())->welfare_InvitedUsers($user_id, $rs5, $rs4['inviteUid'], 4);
//                }
                }
            }
            Db::commit();
            MemcacheClient::getInstance()->delete('userInfo_' . $uid);
            MemcacheClient::getInstance()->delete("userInfo_" . $user_id);
            $userInfo = UserDao::getInstance()->findUserInfoCache($uid);
            return array('code' => 0, 'userInfo' => $userInfo, 'profit' => $profit);
        } catch (Throwable $e) {
            LoggerUtil::write('pay_for_message', ['uid' => $uid, "user_id" => $user_id, "message" => $e->getMessage(), 'line' => $e->getLine(), 'file' => $e->getFile()]);
            Db::rollBack();
            return array('code' => 1, 'msg' => $e->getMessage());
        }
    }


    /**
     * 视频通话 主播获得金币 改为 积分
     * @param $paycall
     * @param $is_anchor_hand_up
     * @return array
     */
    public function getProfitForCall($paycall, $is_anchor_hand_up)
    {
        try {
            Db::beginTransaction();
            if ($paycall['status'] != 1 && $paycall['end_time'] > 0 && $paycall['profit'] == 0) {
                //获取有效通话时长（减去免费时长）
                $keep_time = $paycall['end_time'] - $paycall['start_time'] - $paycall['free_video_time'];

                // 有效通话时长不足（匹配时）
                if (($paycall['match_id'] != 0 && $keep_time <= 1) || $paycall['fare'] == 0) {
                    Db::commit();
                    return array('code' => 1, 'msg' => '成功', 'paycall' => $paycall);
                }

                // 正常视频通话 男用户10秒内挂断女用户没收益（2022.09.05新增）
                if ($paycall['match_id'] == 0 && $keep_time <= 10 && !$is_anchor_hand_up) {
                    Db::commit();
                    return array('code' => 1, 'msg' => '成功', 'paycall' => $paycall);
                }

                if ($keep_time <= PROFIT_INTERVAL / 2) {
                    if ($is_anchor_hand_up) {
                        //女用户30s内主动挂断无积分收入
                        Db::commit();
                        return array('code' => 1, 'msg' => '成功', 'paycall' => $paycall);
                    }
                }

                $keep_minutes = (int)($keep_time / PROFIT_INTERVAL);

                $keep_minutes = $keep_minutes > 0 ? $keep_minutes : 1;

                LoggerUtil::write('get_profit_for_call', ['call_id' => $paycall['id'], $keep_minutes], "settle 1");
                $keep_seconds = (int)($keep_time % PROFIT_INTERVAL);
                $keep_seconds = $keep_seconds == $keep_time ? 0 : $keep_seconds;
                LoggerUtil::write('get_profit_for_call', ['call_id' => $paycall['id'], $keep_seconds], "settle 2");
                if (($keep_seconds < (PROFIT_INTERVAL / 2)) && ($keep_seconds > 0)) {
                    if (!$is_anchor_hand_up) {
                        $keep_minutes = ++$keep_minutes;
                    }
                }
                if ($keep_seconds >= (PROFIT_INTERVAL / 2)) {
                    $keep_minutes = ++$keep_minutes;
                }
                LoggerUtil::write('get_profit_for_call', ['call_id' => $paycall['id'], $keep_minutes]);


                $redis = RedisClient::getInstance();
                $sys_send_count = $redis->get("call_system_send_{$paycall['id']}") ?: 0;
                $recharge_send_count = $redis->get("call_recharge_send_{$paycall['id']}") ?: 0;

                $gold_from = ['gift_count' => $paycall['fare'] - $sys_send_count - $recharge_send_count, 'sys_send_count' => $sys_send_count, 'recharge_send_count' => $recharge_send_count];

                $rate_arr = [];

                $profit = 0;        // 主播收益
                if ($sys_send_count > 0) {
                    $sys_rate = CommonSettingDao::getValue('system_send_gold_rate');
                    $rate_arr['system_send_rate'] = $sys_rate;
                    $profit = bcadd($profit, bcmul($sys_send_count, $sys_rate, 2), 2);
                }
                if ($recharge_send_count > 0) {
                    $res_rate = CommonSettingDao::getValue('recharge_send_gold_rate');
                    $rate_arr['recharge_send_rate'] = $res_rate;
                    $profit = bcadd($profit, bcmul($recharge_send_count, $res_rate, 2), 2);
                }
                if ($paycall['fare'] - $sys_send_count - $recharge_send_count > 0) {
                    $profit = bcadd($profit, bcmul($paycall['fare'] - $sys_send_count - $recharge_send_count, $paycall['rate'], 2), 2);
                }


                LoggerUtil::write('get_profit_for_call', ['call_id' => $paycall['id'], 'sys_send_count' => $sys_send_count, 'recharge_send_count' => $recharge_send_count, 'profit' => $profit, 'rate_arr' => $rate_arr]);

            } else {
                //不给主播结算
                throw new \Exception("已经结算过一次或通话没结束", 0);
            }

            //增加积分
            $call_id = $paycall['id'];
            $userId = $paycall['user_id'];
            $anchorId = $paycall['anchor_id'];

            if ($profit > 0) {
                $anchorInfo = User::findUserInfoById($anchorId);
                if (!$anchorInfo) {
                    throw new \Exception("查询用户信息失败", -5);
                }
                // $userInfo = $this->userModel->find("id,package,channel,version_code", "id=?", [$userId]);
                $userInfo = User::query()->select('id', 'package', 'channel', 'version_code')->where('id', $userId)->first();

                $anchor_income['uid'] = $anchorId;
                $anchor_income['type'] = 1;//收入
                $anchor_income['sub_type'] = $paycall['type'] == 1 ? 2 : 4;//2-视频通话 4-语音通话
                $anchor_income['amount_type'] = 2;
                $anchor_income['user_id'] = $userId;
                $anchor_income['rate'] = $paycall['rate'] * 100;
                $anchor_income['amount'] = $profit;
                $anchor_income['account'] = $anchorInfo['integrate_usable_count'] + $profit;
                $anchor_income['ext'] = json_encode(['p' => $userInfo['package'], 'v' => $userInfo['version_code'], 'c' => $userInfo['channel']]);
                $anchor_income['ctime'] = time();
                $anchor_income['extend'] = $call_id;
                $anchor_income['from'] = intval(\Hyperf\Context\Context::get('cvf')['from']);
                $anchor_income['ip'] = FunUtil::getClientIp();
                $anchor_income['version_code'] = intval(\Hyperf\Context\Context::get('cvf')['version_code']);
                $anchor_income['channel'] = $anchorInfo['channel'] ?? '';
                $anchor_income['package'] = $anchorInfo['package'] ?? '';
                $anchor_income['guild_num'] = $anchorInfo['guild_num'];
                $anchor_income['gold_from'] = json_encode(array_merge($gold_from, $rate_arr));

                // $rs5 = $this->payCallModel->insert($anchor_income, 'tb_income_expense');
                $rs5 = IncomeExpense::query()->insert($anchor_income);
                if (!$rs5) {
                    throw new \Exception("插入收入记录失败", -3);
                }

                $rs3 = UserDao::getInstance()->addAnchorAccount($anchorId, $profit);
                if (!$rs3) {
                    throw new \Exception("增加积分失败", -2);
                }

                $rs3 = PayCallDao::getInstance()->updateCallAnchorAmount($profit, $call_id, $anchorInfo['integrate_usable_count'] + $profit);
                if (!$rs3) {
                    throw new \Exception("更新通话记录失败", -2);
                }

                // 通话表记录用户消耗赠送金币
                $send_gold = bcadd($sys_send_count, $recharge_send_count);
                // $this->payCallModel->execute("update tb_pay_call set ext=json_set(ext,'$.send_gold',{$send_gold}) where id={$paycall['id']}");
                PayCall::query()->where('id', $paycall['id'])->update([
                    'ext' => DB::raw("json_set(ext,'$.send_gold',{$send_gold})")
                ]);

                // 邀请用户分成
                if (!empty($anchorInfo['inviteUid'])) {
                    (new UserWelfareService())->welfare_InvitedUsers($anchorId, $rs5, $anchorInfo['inviteUid'], 4);
                }

            }

            // 视频收益 记录主播排序分值
            // AnchorSortLogModel::record($anchorId,11,intval($profit),'通话id：'.$call_id);


            // $ret = $this->userModel->find('id,inviteUid,gift_count,integrate_usable_count,integrate_freeze_count,session_id', 'id = ?', [$anchorId]);
            $ret = User::query()->select('id,inviteUid,gift_count,integrate_usable_count,integrate_freeze_count,session_id')->where('id', $anchorId)->first();
            //主播任务
            // $setting = new Setting();
            if (intval(SettingDao::getInstance()->getOne('anchor_task_switch')) == 1) {
                AnchorTaskDao::getInstance()->refresh2($paycall['anchor_id'], $paycall['type'], $ret['session_id']);
            }

            $keep_time_1 = intval(($paycall['end_time'] - $paycall['start_time']) / 60);
            if ($keep_time_1 > 0) {
                AnchorDao::getInstance()->addAnchorTime($anchorId, $keep_time_1);
            }

            $paycall['profit'] = $profit;
            $paycall['anchor_account'] += $profit;

            MemcacheClient::getInstance()->delete("userInfo_" . $anchorId);
            if ($keep_time > 180) {
                $userScoreModel = new UserScore();
                $userScoreModel->insertUpdateData($paycall['user_id'], 1, array('total_godvalue' => 1));
                $userScoreModel->insertUpdateData($paycall['anchor_id'], 2, array('total_godvalue' => 1));
            }

            Db::commit();
            return array('code' => 1, 'msg' => '成功', 'paycall' => $paycall);
        } catch (Throwable $e) {
            LoggerUtil::write('get_profit_for_call', $e->getMessage());
            Db::rollBack();
            return array('code' => $e->getCode(), 'msg' => $e->getMessage() . "__" . $e->getFile() . "__" . $e->getLine());
        }
    }


    /**
     * Note - 一方退出房间通知对方挂断
     * DateTime 2024/7/30 16:14
     * User Admin
     * @param $call_id
     * @param $uid
     * @return true|void
     */
    public function noticeOtherHangUp($call_id, $uid)
    {
        $time = time();
        // $paycall = $this->payCallModel->find("*", "id=?", [$call_id]);
        $paycall = PayCall::query()->where('id', $call_id)->first();
        $paycall = modelToArray($paycall);
        LoggerUtil::write('yun_xin_copy_exit_room', $paycall);

        // 通话已结束
        if (empty($paycall) || $paycall['status'] != 0)
            return true;

        $user_id = $paycall['user_id'];
        $anchor_id = $paycall['anchor_id'];

        $update_arr = array('end_time' => $time, 'status' => 1);
        $update_arr['extend'] = 25;

        if ($user_id == $uid) {
            // 结算主播信息
            $balanceData = $this->settleCall($call_id, true, $paycall['anchor_id'], $update_arr);
            $rs['result'] = 1;
            $rs['msg'] = $balanceData;
            $rs['is_call_mass'] = $paycall['is_call_mass'] ?: 0;
            $rs['call_type'] = $paycall['call_type'];
            $this->sendHangUpMsg($user_id, $anchor_id, "对方超时，通话结束", $rs);
        } elseif ($anchor_id == $uid) {
            // 计算用户信息
            $balanceData = $this->settleCall($call_id, false, $paycall['user_id'], $update_arr);
            $rs['result'] = 1;
            $rs['msg'] = $balanceData;
            $rs['is_call_mass'] = $paycall['is_call_mass'] ?: 0;
            $rs['call_type'] = $paycall['call_type'];
            $this->sendHangUpMsg($anchor_id, $user_id, "用户超时，通话结束", $rs);
        }

    }


    /**
     * 云信触发挂断事件后执行
     * @param $call_id
     * @param $uid
     * @param $extend
     */
    public function hangUpCall($call_id, $uid, $extend = 0)
    {
        try {
            $userInfo = User::findUserInfoById($uid);
            $payCallDao = PayCallDao::getInstance();
            $paycall = $payCallDao->getCallCache($call_id, true);
            if (empty($paycall)) {
                // Tool::JSON(\CodeData::NEED_TIPS, '', '通话不存在');
                return formatData('', 200, CodeData::NEED_TIPS, '通话不存在');
            }
            $anchorId = $paycall["anchor_id"];
            $userId = $paycall["user_id"];
            $user_id = $uid == $userId ? $anchorId : $userId;
            if ($userInfo['sex'] == 1) {
                $is_anchor = false;
                $extend_flag = 0;
            } else {
                $is_anchor = true;
                $extend_flag = 10;
            }

            if ($paycall['status'] == 1) {
                //对方或者服务器已经先于自己挂断了
                $desc = '对方已挂断，通话结束';
            } else {
                //要中断通话
                $desc = '通话结束';
                //发起方挂断有三种可能(没接，接了通话还没建立，通话已经建立)
                //接听方挂断有两种可能(通话没建立，通话已经建立)
                if ($paycall['end_time'] == 0) {
                    //通话没建立，告诉对方我放弃了
                    // $rs = $payCallModel->updateByWhere(array('status' => 1, 'extend' => 31 + $extend_flag,'call_wait_time'=>intval(time()-$paycall['ctime'])), "id = $call_id AND status = 0");
                    $rs = PayCall::query()->where('id', $call_id)->where('status', 0)->update(['status' => 1, 'extend' => 31 + $extend_flag, 'call_wait_time' => intval(time() - $paycall['ctime'])]);
                    if (!$rs) {
                        return formatData('', 200, CodeData::NEED_TIPS, '通话已挂断');
                    }

                    MemcacheClient::getInstance()->delete('the_pay_call_' . $call_id);
                    MemcacheClient::getInstance()->delete('last_pay_call_item_' . $anchorId);

                    $this->sendCancelMsg($uid, $user_id, $call_id, $paycall['is_call_mass'], $paycall['type']);

                    // Tool::JSON(\CodeData::SUCCESS, array('result' => -1), $desc);
                    return formatData(['result' => -1], 200, CodeData::NEED_TIPS, $desc);
                }

                // 通话已建立。判断要不要扣费
                if (time() - $paycall['last_pay_time'] >= 60) {
                    if (CHARGE_CALL_VERSION) {
                        $rs = $this->payForCall($paycall);
                        if ($rs['code'] == 1) {
                            $update_arr = array('end_time' => time(), 'status' => 1, 'extend' => 32 + $extend_flag);

                        } elseif ($rs['code'] == -1) {
                            //扣费失败，中断此次通话
                            $update_arr = array('status' => 1, 'extend' => 33 + $extend_flag);
                        } else {
                            $update_arr = array('end_time' => time(), 'status' => 1, 'extend' => 35 + $extend_flag);
                        }
                    }
                } else {
                    $update_arr = array('end_time' => time(), 'status' => 1, 'extend' => 34 + $extend_flag);
                }

                // 男用户10秒内主动挂断通话
                if (time() - $paycall['start_time'] < 10 && $userInfo['sex'] == 1 && $userInfo['noble'] != 1 && $userInfo['super_noble'] != 1) {
                    $redis = RedisClient::getInstance();
                    $hangUpCount = $redis->get("free_call:hang_up_{$uid}");
                    // 过期时间
                    $etime = strtotime(date('Y-m-d') . '23:59:59') + 1 - time();
                    if ($hangUpCount) {
                        $redis->setex("free_call:hang_up_{$uid}", $etime, $hangUpCount + 1);
                    } else {
                        $redis->setex("free_call:hang_up_{$uid}", $etime, 1);
                    }
                }

            }

            $balanceData = [];
            if (CHARGE_CALL_VERSION) {
                //结算
                $balanceData = $this->settleCall($call_id, $is_anchor, $uid, $update_arr, $extend);
            }

            // Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'msg' => $balanceData), $desc);
            return formatData(['result' => 1, 'msg' => $balanceData], 200, CodeData::SUCCESS, $desc);
        } catch (Throwable $e) {
            // Tool::JSON(\CodeData::NEED_TIPS, '', $e->getMessage());
            return formatData('', 200, CodeData::NEED_TIPS, $e->getMessage());
        }
    }


    /**
     * 给用户发送`对方已取消`消息
     * @param $uid
     * @param $to_uid
     * @param $call_id
     * @param int $is_call_mass
     * @param int $call_type
     * @return void
     */
    public function sendCancelMsg($uid, $to_uid, $call_id, int $is_call_mass = 0, int $call_type = 1): void
    {
        $insertData['uid'] = $uid;
        $insertData['receive_uid'] = (int)$to_uid;
        $insertData['content'] = '对方已取消';
        $insertData['ctime'] = time();
        $insertData['chat_type'] = 9;  //拒绝通知
        $insertData['content_type'] = 4; // 4：视频通话请求，5：语音通话请求
        $insertData['from'] = 1;
        $call_data = array('call_id' => $call_id, 'call_type' => $call_type, 'is_call_mass' => $is_call_mass);
        $insertData = $this->getCallArr($call_data, $insertData, $uid, $to_uid);

        //通过socket消息转发，不再通过mongo表记录
        $socket_data = array('uid_list' => array($to_uid), 'message' => $insertData);
        // Fun::socket_client('send_message', $uid, "", $socket_data);
        // $this->send_message(["uid"=>$uid,'data'=>$socket_data]);
        $wyyClientService = new WyyClientService();
        $wyyClientService->send_message(["uid" => $uid, 'data' => $socket_data]);
    }


    /**
     * 给用户发送挂断消息
     * @param $uid
     * @param $to_uid
     * @param $msg
     * @param $call_data
     */
    public function sendHangUpMsg($uid, $to_uid, $msg, $call_data): void
    {
        $insertData['uid'] = $uid;
        $insertData['receive_uid'] = (int)$to_uid;
        $insertData['content'] = $msg;
        $insertData['ctime'] = time();
        $insertData['chat_type'] = 101;  // 挂断通知
        $insertData['content_type'] = 4; // 4：视频通话请求，5：语音通话请求
        $insertData['from'] = 1;
        $insertData = $this->getCallArr($call_data, $insertData, $uid, $to_uid);

        //通过socket消息转发，不再通过mongo表记录
        $socket_data = array('uid_list' => array($to_uid));
        $socket_data['message'] = $insertData;
        // Fun::socket_client('send_message', $uid, "", $socket_data);
        $wyyClientService = new WyyClientService();
        $wyyClientService->send_message(["uid" => $uid, 'data' => $socket_data]);
    }


    /**
     * 给用户发送`黑屏对方`消息
     * @param $uid
     * @param $to_uid
     * @param $call_id
     * @param int $call_type
     */
    public function sendBlackScreenMsg($uid, $to_uid, $call_id, int $call_type = 1): void
    {
        //插入mongo，告诉发送方系统已牵线
        $insertData['uid'] = (int)$uid; //接听方
        $insertData['receive_uid'] = (int)$to_uid;   //发起方
        $insertData['content'] = '对方已黑屏';
        $insertData['ctime'] = time();
        $insertData['chat_type'] = 13;  //牵线通知
        $insertData['content_type'] = 4; // 4：视频通话请求，5：语音通话请求
        $insertData['from'] = 1;
        $call_data = array('call_id' => $call_id, 'call_type' => $call_type);
        $insertData['call_data'] = json_encode($call_data);
        $insertData['look'] = 0;  //是否已读
        $insertData['date'] = date("Y-m-d");
        $insertData['free_video'] = 0;
        //通过socket消息转发，不再通过mongo表记录
        $socket_data = array('uid_list' => array($to_uid), 'message' => $insertData);
        // Fun::socket_client('send_message', $uid, "", $socket_data);
        $wyyClientService = new WyyClientService();
        $wyyClientService->send_message(["uid" => $uid, 'data' => $socket_data]);
    }

    /**
     * 给用户发送`取消黑屏`消息
     * @param $uid
     * @param $to_uid
     * @param $call_id
     * @param int $call_type
     */
    public function cancelBlackScreenMsg($uid, $to_uid, $call_id, int $call_type = 1): void
    {
        $insertData['uid'] = (int)$uid; //发送方
        $insertData['receive_uid'] = (int)$to_uid;   //接收方
        $insertData['content'] = '取消黑屏';
        $insertData['ctime'] = time();
        $insertData['chat_type'] = 14;  //取消黑屏通知
        $insertData['content_type'] = 4; // 4：视频通话请求，5：语音通话请求
        $insertData['from'] = 1;
        $call_data = array('call_id' => $call_id, 'call_type' => $call_type);
        $insertData['call_data'] = json_encode($call_data);
        // $insertData['look'] = 0;  //是否已读
        // $insertData['date'] = date("Y-m-d");
        // $insertData['free_video'] = 0;
        //通过socket消息转发，不再通过mongo表记录
        $socket_data = array('uid_list' => array($to_uid), 'message' => $insertData);
        // Fun::socket_client('send_message', $uid, "", $socket_data);
        $wyyClientService = new WyyClientService();
        $wyyClientService->send_message(["uid" => $uid, 'data' => $socket_data]);

    }


    /**
     * Note - 给用户发送`已拒接`消息
     * DateTime 2024/8/21 12:31
     * User Admin
     * @param $uid
     * @param $to_uid
     * @param $call_id
     * @param $is_call_mass
     * @param $call_type
     */
    public function sendRefuseMsg($uid, $to_uid, $call_id, $is_call_mass, $call_type = 1)
    {
        $insertData['uid'] = (int)$uid; //接听方
        $insertData['receive_uid'] = (int)$to_uid;   //发起方
        $insertData['content'] = trans('message.对方拒接');
        $insertData['ctime'] = time();
        $insertData['chat_type'] = 9;  //拒绝通知
        $insertData['content_type'] = 4; // 4：视频通话请求，5：语音通话请求
        $insertData['from'] = 1;
        $call_data = [
            'call_id' => $call_id,
            'call_type' => $call_type,
            'is_call_mass' => $is_call_mass,
        ];
        $insertData['call_data'] = json_encode($call_data);
        $insertData['look'] = 0;  //是否已读
        $insertData['date'] = date("Y-m-d");
        $insertData['free_video'] = 0;

        $userModel = UserDao::getInstance();
        // 增加用户亲密度
        if (User::where('id', $uid)->value('sex') == 1) {
            $uuid = $uid;
            $anchor_id = $to_uid;
        } else {
            $uuid = $to_uid;
            $anchor_id = $uid;
        }
        $insertData['closeness'] = ClosenessDao::read($uuid, $anchor_id);
        // 是否是新人
        $insertData['is_new_user'] = $userModel->checkNewUser($uid);

        //通过socket消息转发，不再通过mongo表记录
        $socket_data = array('uid_list' => array($to_uid), 'message' => $insertData);
        // Fun::socket_client('send_message', $uid, "", $socket_data);
        // $this->send_message(["uid" => $uid, 'data' => $socket_data]);
        $wyyClientService = new WyyClientService();
        $wyyClientService->send_message(["uid" => $uid, 'data' => $socket_data]);
    }


    /**
     * Note - 给用户发送`已接听`消息
     * DateTime 2024/8/21 12:35
     * User Admin
     * @param $uid
     * @param $to_uid
     * @param $call_id
     * @param $is_call_mass
     * @param $call_type
     */
    public function sendAnswerMsg($uid, $to_uid, $call_id, $is_call_mass, $call_type = 1)
    {
        $insertData['uid'] = (int)$uid; //接听方
        $insertData['receive_uid'] = (int)$to_uid;   //发起方
        $insertData['content'] = trans('message.对方已接听');
        $insertData['ctime'] = time();
        $insertData['chat_type'] = 20;  //拒绝通知
        $insertData['content_type'] = 4; // 4：视频通话请求，5：语音通话请求
        $insertData['from'] = 1;
        $call_data = ['call_id' => $call_id, 'call_type' => $call_type, 'is_call_mass' => $is_call_mass];
        $insertData['call_data'] = json_encode($call_data);
        $insertData['look'] = 0;  //是否已读
        $insertData['date'] = date("Y-m-d");
        $insertData['free_video'] = 0;

        // 增加用户亲密度
        if (User::where('id', $uid)->value('sex') == 1) {
            $uuid = $uid;
            $anchor_id = $to_uid;
        } else {
            $uuid = $to_uid;
            $anchor_id = $uid;
        }
        $insertData['closeness'] = ClosenessDao::read($uuid, $anchor_id);

        // 是否是新人
        $insertData['is_new_user'] = UserDao::getInstance()->checkNewUser($uid);

        //通过socket消息转发，不再通过mongo表记录
        $socket_data = array('uid_list' => array($to_uid), 'message' => $insertData);
        // Fun::socket_client('send_message', $uid, "", $socket_data);
        // $this->send_message(["uid" => $uid, 'data' => $socket_data]);
        $wyyClientService = new WyyClientService();
        $wyyClientService->send_message(["uid" => $uid, 'data' => $socket_data]);
    }


    /**
     * Note - 给用户发送`未接听`消息
     * DateTime 2024/8/21 12:31
     * User Admin
     * @param $uid
     * @param $to_uid
     * @param $call_id
     * @param $is_call_mass
     * @param $call_type
     * @return true
     */
    public function sendUnAnswerMsg($uid, $to_uid, $call_id, $is_call_mass = 0, $call_type = 1)
    {
        $insertData['uid'] = (int)$uid; //接听方
        $insertData['receive_uid'] = (int)$to_uid;   //发起方
        $insertData['content'] = trans('message.无人接通');
        $insertData['ctime'] = time();
        $insertData['chat_type'] = 9;  //拒绝通知
        $insertData['content_type'] = 4; // 4：视频通话请求，5：语音通话请求
        $insertData['from'] = 1;
        $call_data = array('call_id' => $call_id, 'call_type' => $call_type, 'is_call_mass' => $is_call_mass);
        $insertData['call_data'] = json_encode($call_data);
        $insertData['look'] = 0;  //是否已读
        $insertData['date'] = date("Y-m-d");
        $insertData['free_video'] = 0;

        // $userModel = new UserModel();
        // 增加用户亲密度
        if (User::where('id', $uid)->value('sex') == 1) {
            $uuid = $uid;
            $anchor_id = $to_uid;
        } else {
            $uuid = $to_uid;
            $anchor_id = $uid;
        }
        $insertData['closeness'] = ClosenessDao::read($uuid, $anchor_id);
        // 是否是新人
        $insertData['is_new_user'] = UserDao::getInstance()->checkNewUser($uid);

        //通过socket消息转发，不再通过mongo表记录
        $socket_data = array('uid_list' => array($to_uid), 'message' => $insertData);
        // Fun::socket_client('send_message', $uid, "", $socket_data);
        // $this->send_message(["uid" => $uid, 'data' => $socket_data]);
        $wyyClientService = new WyyClientService();
        $wyyClientService->send_message(["uid" => $uid, 'data' => $socket_data]);
        return true;
    }


    /**
     * Note - 通话消息记录组装
     * DateTime 2024/8/2 12:38
     * User Admin
     * @param array $call_data
     * @param array $insertData
     * @param $uid
     * @param $to_uid
     * @return array
     */
    public function getCallArr(array $call_data, array $insertData, $uid, $to_uid): array
    {
        $insertData['call_data'] = json_encode($call_data);
        $insertData['look'] = 0;  //是否已读
        $insertData['date'] = date("Y-m-d");
        $insertData['free_video'] = 0;

        // 增加用户亲密度
        if (User::query()->where('id', $uid)->value('sex') == 1) {
            $uuid = $uid;
            $anchor_id = $to_uid;
        } else {
            $uuid = $to_uid;
            $anchor_id = $uid;
        }
        $insertData['closeness'] = ClosenessDao::read($uuid, $anchor_id);
        // 是否是新人
        $insertData['is_new_user'] = UserDao::getInstance()->checkNewUser($uid);
        return $insertData;
    }

    /**
     * Note - 用户消费记录数据组装
     * DateTime 2024/8/2 12:41
     * User Admin
     * @param mixed $message_id
     * @param array $user_expense
     * @param $rs0
     * @return array
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function getExpense(mixed $message_id, array $user_expense, $rs0): array
    {
        $user_expense['extend'] = $message_id;
        $user_expense['from'] = intval($rs0['from']);
        $user_expense['ip'] = FunUtil::getClientIp();
        $user_expense['version_code'] = intval($rs0['version_code']);
        $user_expense['channel'] = $rs0['channel'];
        $user_expense['package'] = $rs0['package'];
        $user_expense['guild_num'] = '';
        return $user_expense;
    }


}